// DailyQuestionServiceImpl.java
package com.scuec.groupfive.service.impl;

import com.scuec.groupfive.entity.QuestionInfo;
import com.scuec.groupfive.mapper.DailyQuestionMapper;
import com.scuec.groupfive.service.DailyQuestionService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.HashMap;
import java.util.Map;

@Service
public class DailyQuestionServiceImpl implements DailyQuestionService {

    @Autowired
    private DailyQuestionMapper dailyQuestionMapper;

    @Override
    public QuestionInfo getTodayQuestion() {
        return dailyQuestionMapper.selectTodayQuestion();
    }

    @Override
    public int addToFavorites(Long userId, Long questionId) {
        if (dailyQuestionMapper.isFavorite(userId, questionId) > 0) {
            return 0;
        }
        return dailyQuestionMapper.insertFavorite(userId, questionId);
    }

    @Override
    public int removeFromFavorites(Long userId, Long questionId) {
        return dailyQuestionMapper.deleteFavorite(userId, questionId);
    }

    @Override
    public boolean isQuestionInFavorites(Long userId, Long questionId) {
        return dailyQuestionMapper.isFavorite(userId, questionId) > 0;
    }

    @Override
    public Map<String, Object> getAnswerAndAnalysis(Long questionId, String questionType) {
        Map<String, Object> result = new HashMap<>();

        if ("single_choice".equalsIgnoreCase(questionType)) {
            result = dailyQuestionMapper.selectChoiceAnswer(questionId);
            result.put("answer", result.get("choice_answer"));
            result.put("analysis", result.get("choice_analysis"));
        } else if ("fill_in_the_blank".equalsIgnoreCase(questionType)) {
            result = dailyQuestionMapper.selectFillBlankAnswer(questionId);
            result.put("answer", result.get("answer_template"));
            result.put("analysis", result.get("fillblank_analysis"));
        }

        return result;
    }

    @Override
    public int submitAnswer(Long userId, Long questionId, String questionType,
                            String answer, Boolean isCorrect, Double score, Integer timeSpent) {
        return dailyQuestionMapper.insertAnswerRecord(userId, questionId, questionType,
                answer, isCorrect, score, timeSpent);
    }
}